package com.ruoyi.zsix.service.manager;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ZSixSecurityUtiles;
import com.ruoyi.zsix.domain.orgmanagement.DepartmentEntity;
import com.ruoyi.zsix.mapper.UserInfoMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Component
@RequiredArgsConstructor
public class CommManager {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private ZSixSecurityUtiles zSixSecurityUtiles;
    /**
     * 获取当前系统登陆人
     * @return
     */
    public String getUserNo(){
        return SecurityUtils.getUsername();
    }

    /**
     * 避免AuthenticationContextHolder丢失，重新将用户信息注入Security
     * @return
     */
    public String InitSecurityContextHolder(){
        SysUser user=userInfoMapper.getUserInfo(this.getUserNo());
        Set<String> perms = new HashSet<String>();
        perms.add("ROLE_ACTIVITI_USER");
        LoginUser loginUser=new LoginUser(user.getUserId(),user.getDeptId(),user,perms);
        zSixSecurityUtiles.logInAs(loginUser);
        return user.getUserName();
    }
    /**
     * 递归查找当前部门的子部门
     * @param root 单个对象
     * @param all 所有的集合
     * @return 排序后的子类
     */
    public List<DepartmentEntity> getDeptChildren(DepartmentEntity root, List<DepartmentEntity> all){
        List<DepartmentEntity> childrenList = all.stream()
                .filter(t -> t.getParentId() == root.getId())
                .map(g -> {
                    //找子菜单
                    g.setChildren(getDeptChildren(g,all));
                    return g;
                })
                //菜单排序
                .collect(Collectors.toList());

        return childrenList;
    }
}
